import tkinter as tk
from tkinter import ttk, messagebox
import os
import sys


from gui.add_window import AddEmployeeWindow  # 导入添加窗口
from gui.search_window import SearchEmployeesWindow
from gui.view_window import ViewEmployeesWindow

class IconicWindow:
    """图标窗口基类（混合模式设计）"""

    def __init__(self, master, title, icon_path):
        self.master = master
        self.title = title
        self.icon_path = icon_path

        # 统一图标设置逻辑
        self._set_window_icon()

    def _set_window_icon(self):
        """智能设置窗口图标"""
        if self.icon_path:
            try:
                if isinstance(self.master, tk.Tk):
                    # 主窗口特殊处理（Windows系统）
                    if sys.platform == "win32":
                        self.master.iconbitmap(self.icon_path)
                    else:
                        # 其他系统使用photoimage方式
                        img = tk.PhotoImage(file=self.icon_path)
                        self.master.call('wm', 'iconphoto', self.master._w, img)
                else:
                    # 子窗口处理
                    self.master.iconbitmap(self.icon_path)
            except Exception as e:
                messagebox.showwarning("图标加载失败",
                                       f"图标加载失败：{os.path.basename(self.icon_path)}\n"
                                       f"错误详情：{str(e)}\n"
                                       f"当前路径：{os.path.abspath(self.icon_path)}")


class MainApp:
    def __init__(self, root):
        self.root = root
        self.root.title("职工管理系统")

        # 初始化窗口尺寸和位置
        window_width = 450
        window_height = 150
        self.root.geometry(f"{window_width}x{window_height}")
        self.center_window(window_width, window_height)

        # 设置图标（使用混合基类）
        self.icon_path = "asset/OIP-C.ico"  # 相对路径
        IconicWindow(self.root, "主窗口", self.icon_path)

        # 创建界面元素...
        main_frame = ttk.Frame(self.root, padding=20)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 创建功能按钮（前三个）
        buttons = [
            ("信息录入", self.open_add_window),
            ("信息管理", self.open_InformationManagement_window),
            ("信息查询", self.open_search_window)
        ]

        # 按钮布局（3列自动换行）
        for i, (text, cmd) in enumerate(buttons):
            btn = ttk.Button(
                main_frame,
                text=text,
                command=cmd,
                width=15
            )
            btn.grid(row=i // 3, column=i % 3, padx=10, pady=10)

        # 创建退出系统按钮（单独布局）
        exit_btn = ttk.Button(
            main_frame,
            text="退出系统",
            command=self.exit_system,
            width=15
        )
        exit_btn.grid(row=1, column=2, sticky="se", padx=(0, 10), pady=10)

        # 配置网格权重使退出按钮保持在右下角
        main_frame.grid_columnconfigure(2, weight=1)
        main_frame.grid_rowconfigure(1, weight=1)

        # 以下是各功能窗口打开方法

    def open_add_window(self):
        """ 打开信息录入窗口 """
        try:
            add_window = AddEmployeeWindow(self.root)
        except Exception as e:
            messagebox.showerror("错误", f"打开窗口失败: {str(e)}")

    def open_InformationManagement_window(self):
        try:
            view_window = ViewEmployeesWindow(self.root)
        except Exception as e:
            messagebox.showerror("错误", f"打开窗口失败: {str(e)}")

    def open_search_window(self):
        try:
            search_window = SearchEmployeesWindow(self.root)
        except Exception as e:
            messagebox.showerror("错误", f"打开窗口失败: {str(e)}")

    def exit_system(self):
        if messagebox.askokcancel("退出确认", "确定要退出系统吗？"):
            self.root.destroy()

    def center_window(self, width, height):
        """将窗口居中显示"""
        # 获取屏幕尺寸
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()

        # 计算位置坐标
        x = (screen_width // 2) - (width // 2)
        y = (screen_height // 2) - (height // 2)

        # 设置窗口位置
        self.root.geometry(f"+{x}+{y}")


# 启动应用
if __name__ == "__main__":
    root = tk.Tk()
    app = MainApp(root)
    root.mainloop()
